package com.tool.lock.sync;

/**
 * @author 酒徒
 * @Version 1.0
 * @data 2025/6/29 17:39
 */
public class SyncTest {
    private static boolean isPrintA = true;
    public static void main(String[] args) {
        SyncTest syncTest = new SyncTest();
        syncTest.printA();
        syncTest.printB();
    }

    public void printA() {
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                synchronized (this) {
                    while (!isPrintA) {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("A");
                    isPrintA = false;
                    notifyAll();
                }
            }
        }).start();
    }

    public synchronized void printB() {
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                synchronized (this) {
                    while (isPrintA) {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("B");
                    isPrintA = true;
                    notifyAll();
                }
            }
        }).start();
    }


}


